package com.jwiki.app.jkeeper.controller;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.jwiki.app.jkeeper.common.CommonException;
import com.jwiki.app.jkeeper.common.data.Context;
import com.jwiki.app.jkeeper.common.data.Response;
import com.jwiki.app.jkeeper.controller.form.UserForm;
import com.jwiki.app.jkeeper.repository.model.UserModel;
import com.jwiki.app.jkeeper.service.UserService;

import freemarker.template.Configuration;
import freemarker.template.Template;

@RestController
public class UserAuthController extends BaseController {

    @Autowired
    private Configuration configuration;

    @Autowired
    private JavaMailSenderImpl mailSender;

    @Autowired
    private UserService userService;

    @RequestMapping("/auth/login")
    public Response login(@RequestBody UserForm form, HttpSession session) {
        Response response = getResponse();

        checkKaptcha(form, session);

        UserModel model = userService.getUserByName(form.getName());
        if (model == null) {
            throw new CommonException("用户名不存在！");
        } else {
            if (model.getPassword().equals(DigestUtils.md5Hex(form.getPassword()))) {
                Context context = getContext();
                context.setUserId(model.getId());
                context.setUserName(model.getName());
                session.setAttribute(Context.AUTH_INFO_KEY, context);
                response.setSuccess(true);
            } else {
                throw new CommonException("用户名或密码不正确！");
            }
        }

        return response;
    }

    @RequestMapping("/auth/logout")
    public Response logout(HttpSession session) {
        session.removeAttribute(Context.AUTH_INFO_KEY);
        Response response = getResponse();
        response.setSuccess(true);
        return response;
    }

    @RequestMapping("/auth/regist")
    public Response regist(@RequestBody UserForm form, HttpSession session) {
        Response response = getResponse();

        checkKaptcha(form, session);

        UserModel model = userService.getUserByName(form.getName());
        if (model == null) {
            model = userService.getUserByEmail(form.getEmail());
            if (model == null) {
                response.setSuccess(userService.saveUser(form));
            } else {
                throw new CommonException("邮箱已使用，请更换邮箱！");
            }
        } else {
            throw new CommonException("用户名已注册，请更换用户名！");
        }

        return response;
    }

    @RequestMapping("/auth/reset")
    public Response reset(@RequestBody UserForm form, HttpSession session) throws Exception {
        Response response = getResponse();

        checkKaptcha(form, session);

        UserModel model = userService.getUserByEmail(form.getEmail());
        if (model == null) {
            throw new CommonException("邮箱不存在，无法发送邮件！");
        } else {
            String password = RandomStringUtils.random(8, true, true);
            Map<String, Object> data = new HashMap<>();
            data.put("username", model.getName());
            data.put("password", password);
            // handle mail template
            StringWriter out = new StringWriter();
            Template template = configuration.getTemplate("password.html");
            template.process(data, out);

            // send mail
            MimeMessageHelper message = new MimeMessageHelper(mailSender.createMimeMessage(), "UTF-8");
            message.setFrom(mailSender.getUsername());
            message.setTo(form.getEmail());
            message.setSubject("金管家-重置密码");
            message.setText(out.toString(), true);
            mailSender.send(message.getMimeMessage());

            // update password
            model.setPassword(password);
            BeanUtils.copyProperties(model, form);
            response.setSuccess(userService.saveUser(form));
        }

        return response;
    }

    @RequestMapping("/user/savePassword")
    public Response savePassword(@RequestBody UserForm form) {
        Response response = getResponse();
        form.setId(getContext().getUserId());
        response.setSuccess(userService.savePassword(form));
        return response;
    }

    protected void checkKaptcha(UserForm form, HttpSession session) {
        String kaptcha = (String) session.getAttribute(Context.KAPTCHA_KEY);
        if (!form.getKaptcha().equalsIgnoreCase(kaptcha)) {
            throw new CommonException("验证码不正确！");
        }
    }

}
